package giermala.dominik.fotka.service;


import giermala.dominik.fotka.domain.Role;
import giermala.dominik.fotka.domain.User;
import giermala.dominik.fotka.repository.UserRepository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class CustomUserDetailsService implements UserDetailsService {

	private static final Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);
	
	@Autowired private UserRepository userRepository;
	@Autowired private PasswordEncoder passwordEncoder;
	@Autowired private SaltSource saltSource;
	
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		try {
			User user = userRepository.findByUsername(username);
			if (user == null) {
				throw new UsernameNotFoundException("username: "+username);
			}
			return user;
		} catch (Exception e) {
			logger.info("user Load By Username Exception: "+ e.getMessage());
			throw new RuntimeException(e);
		}
	}

	public void saveUser(giermala.dominik.fotka.domain.User domainUser) {
		Role role = new Role();
		role.setFotkaUser(domainUser);
		role.setRole(1);
		domainUser.setRole(role);

		String plainTextPassword = domainUser.getPassword();
		Object salt = saltSource.getSalt(domainUser);
		String encodedPassword = passwordEncoder.encodePassword(plainTextPassword, salt);
		domainUser.setPassword(encodedPassword);
	    userRepository.saveAndFlush(domainUser);
	} 
}